﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NLog;
using DAL;
using Entity;
using System.IO;
using System.Drawing.Imaging;
using System.Xml;
using System.Configuration;
using System.Text;
using System.Security.Cryptography;
using System.Net;
using Newtonsoft.Json.Linq;

public partial class AddArticles : System.Web.UI.Page
{
    private static Logger _logger = LogManager.GetCurrentClassLogger();

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            PageTitle.Text = "موقع لايف كورة | إضافة مقالة جديدة";
            if (!IsPostBack)
            {
                if (FormsFunction.GetLiveKoraCookie() != null)
                {
                }
                else
                {
                    Response.Redirect("/", false);
                }
            }
        }
        catch (Exception ex)
        {
            _logger.Error("Admin_AddArticalsIframe:::Page_Load:::" + ex.Message);
        }
    }

    private void ErrorResult()
    {
        Response.Clear();
        Response.StatusCode = 404;
        Response.End();
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            string[] arrUserInfo = FormsFunction.GetLiveKoraCookie();

            Articls objArticls = new Articls();
            ManageArticls objManageArticls = new ManageArticls();
            objArticls.ArticlsTitle = txtArticlsTitle.Text;
            if (editor.InnerText.Length > 100)
            {
                objArticls.ArticlsSmallDescription = editor.Value.Substring(0, 100).Replace("<p style=\"direction: rtl;\">", "").Replace("<p>", "").Replace("</p>", "");
            }
            else
            {
                objArticls.ArticlsSmallDescription = editor.Value.Substring(0, editor.InnerText.Length - 1).Replace("<p style=\"direction: rtl;\">", "").Replace("<p>", "").Replace("</p", "");
            }
            objArticls.CategoryID = 26;
            objArticls.IsFeatures = 0;

            if (fuArticlsImage2.HasFile)
            {
                string newname = "LiveKora_" + Guid.NewGuid().ToString();
                string extension = Path.GetExtension(fuArticlsImage2.PostedFile.FileName);
                string sFile2Path = Server.MapPath("~/ArticalsImage/Full/" + newname + extension);
                fuArticlsImage2.SaveAs(sFile2Path);
                CompressJpeg(sFile2Path, 55);
                objArticls.ArticlsImage = "../ArticalsImage/Full/" + newname + extension;
                objArticls.ArticlsThumb = "../ArticalsImage/Full/" + newname + extension;
            }
            else
            {
                if (string.IsNullOrEmpty(hfImageFull.Value))
                {
                    objArticls.ArticlsImage = "null";
                    objArticls.ArticlsThumb = "null";
                }
                else
                {
                    objArticls.ArticlsImage = hfImageFull.Value;
                    objArticls.ArticlsThumb = hfImageFull.Value;
                }
            }
            objArticls.PublisherName = arrUserInfo[0].ToString();
            objArticls.ArticlsFullDescription = editor.InnerText;
            objArticls.ArticlsVedio = txtArticlsVedioCode.Text;
            objArticls.ArticlsStatus = 0;
            if (!string.IsNullOrEmpty(ArticlsID.Value))
            {
                objArticls.ArticlsID = Convert.ToInt32(ArticlsID.Value);
                int nReturnValue = objManageArticls.EditArticlsInfo(objArticls);
                if (nReturnValue == 1)
                    Response.Redirect("~/UserArticles", false);

                else
                    tr_UserMessage.InnerHtml = "هناك مشكلة في الموقع الرجاء المحاولة فيما بعد";
            }
            else
            {
                int nReturnValue = (int)objManageArticls.AddNewArticls(objArticls);
                if (nReturnValue != 0)
                {
                    //SiteMapGenerater(string.Format("http://www.livekora.net/Articles/{0}/", nReturnValue, ""), DateTime.Now.ToString(), "daily", "0.69");
                    tr_UserMessage.InnerHtml = "لقد تم إضافة المقالة بنجاح";
                    txtArticlsTitle.Text = string.Empty;
                    txtArticlsVedioCode.Text = string.Empty;
                    editor.InnerText = string.Empty; 
                    txtArticlsTitle.Focus();
                }
                else
                {
                    tr_UserMessage.InnerHtml = "هناك مشكلة في الموقع الرجاء المحاولة فيما بعد";
                }
            }
        }
        catch (Exception ex)
        {
            _logger.Error("Admin_AddArticalsIframe:::btnSubmit_Click:::" + ex.Message);
            throw;
        }
    }

    public void CompressJpeg(string path, int quality)
    {
        FileInfo objFileInfo;
        using (System.Drawing.Image source = System.Drawing.Image.FromFile(path))
        {
            ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders().First(c => c.MimeType == "image/jpeg");
            EncoderParameters parameters = new EncoderParameters(3);
            parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 40L);
            parameters.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.ScanMethod, (int)EncoderValue.ScanMethodInterlaced);
            parameters.Param[2] = new EncoderParameter(System.Drawing.Imaging.Encoder.RenderMethod, (int)EncoderValue.RenderProgressive);
            objFileInfo = new FileInfo(path);
            source.Save(Server.MapPath("~/ArticalsImage/x/") + objFileInfo.Name, codec, parameters);
        }

        File.Delete(Server.MapPath("~/ArticalsImage/Full/") + objFileInfo.Name);
        File.Move(Server.MapPath("~/ArticalsImage/x/") + objFileInfo.Name, Server.MapPath("~/ArticalsImage/Full/") + objFileInfo.Name);

    }

    protected void btnGetAllUserTwiite_Click(object sender, EventArgs e)
    {
        try
        {
            
        }
        catch (Exception ex)
        {
            _logger.Error("Admin_AddArticalsIframe:::btnGetAllUserTwiite_Click:::" + ex.Message);
        }
    }

    public void SiteMapGenerater(string loc, string lastmod, string changefreq, string priority)
    {
        //_root root for new element
        // path sitemap physical location eg sitemap.xml  (at root)

        string path = "../sitemap/sitemap.xml";
        try
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(HttpContext.Current.Server.MapPath(path));
            XmlNode snippet = doc.CreateNode(XmlNodeType.Element, "url", doc.DocumentElement.NamespaceURI);
            XmlNode _loc = doc.CreateNode(XmlNodeType.Element, "loc", doc.DocumentElement.NamespaceURI);

            _loc.InnerText = HttpUtility.UrlDecode(loc);
            XmlNode _lastmod = doc.CreateNode(XmlNodeType.Element, "lastmod", doc.DocumentElement.NamespaceURI);
            _lastmod.InnerText = DateTime.Now.ToString("yyyy-MM-dd");
            XmlNode _changefreq = doc.CreateNode(XmlNodeType.Element, "changefreq", doc.DocumentElement.NamespaceURI);
            _changefreq.InnerText = changefreq;
            XmlNode _priority = doc.CreateNode(XmlNodeType.Element, "priority", doc.DocumentElement.NamespaceURI);
            _priority.InnerText = priority;
            snippet.AppendChild(_loc);
            snippet.AppendChild(_lastmod);
            snippet.AppendChild(_changefreq);
            snippet.AppendChild(_priority);
            int cnt = doc.ChildNodes.Count;
            int g = snippet.Attributes.Count;
            doc.ChildNodes.Item(cnt - 1).AppendChild(snippet);
            doc.Save(HttpContext.Current.Server.MapPath(path));
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    protected string GetThumnb(string sYoutubeURL)
    {
        try
        {
            string[] parts = sYoutubeURL.Split(new[] { "=" }, int.MaxValue, StringSplitOptions.None);
            return parts[1];
        }
        catch (Exception)
        {
            return "null";
        }
    }
 
}